const express = require('express');
const router = express.Router();
const requirementAnalysisService = require('../service/requirementAnalysisService');

// 测试 Confluence 页面访问
router.get('/api/test-confluence-access', async (req, res) => {
  try {
    const url = 'http://192.168.2.200:8090/pages/viewpage.action?pageId=75667598';
    const username = 'gushan';
    const password = '123456';
    
    console.log('开始测试 Confluence 页面访问...');
    console.log('URL:', url);
    console.log('用户名:', username);
    
    const result = await requirementAnalysisService.fetchAndParse(url, username, password);
    
    res.json({ 
      success: true, 
      message: '页面访问成功',
      data: {
        pageTitle: result.pageTitle,
        sectionCount: result.sections.length,
        sections: result.sections.map(sec => ({
          title: sec.title,
          fieldCount: sec.fields.length,
          headers: sec.headers,
          sampleFields: sec.fields.slice(0, 3).map(f => ({
            label: f.label,
            area: f.area,
            inListPage: f.inListPage,
            inBodyPage: f.inBodyPage
          }))
        })),
        structure: result.structure
      }
    });
  } catch (error) {
    console.error('测试失败:', error.message);
    res.status(500).json({ success: false, message: error.message });
  }
});

// 解析需求文档
router.post('/api/analyze-requirement', async (req, res) => {
  try {
    const { url, username, password } = req.body;
    
    if (!url) {
      return res.status(400).json({ success: false, message: '请输入文档地址' });
    }

    const result = await requirementAnalysisService.fetchAndParse(url, username, password);
    
    res.json({ success: true, data: result });
  } catch (error) {
    console.error('Requirement analysis error:', error);
    res.status(500).json({ success: false, message: error.message });
  }
});

module.exports = router;
